<?php

namespace app\common\models;

class QbRecord extends BaseModel
{
    protected $name = 'qb_record';
    protected $pk = 'record_id';
    // 已参加
    const isJoin = 1;
    // 未参加
    const unJoin = 0;
    // 兑换中
    const EXCHANGE_IN = 0;
    // 已兑换
    const EXCHANGE_SUCCESS = 1;
    // 兑换失败
    const EXCHANGE_FAIL = 2;

    public function topUp($param)
    {
        $sys_config = new SysConfig();
        $rule = $sys_config->getActivityInfo(true);
        $order_where = [];
        $record_where = [];
        if (intval($param['is_activity']) == self::isJoin){
            // 获取活动时间
            $beg_time = empty($rule['beg_time']) ? '' : strtotime($rule['beg_time']);
            $end_time = empty($rule['end_time']) ? '' : strtotime($rule['end_time']);
            if ($beg_time > NEW_TIME){
                return self::setError('活动未开始');
            }
            if ($end_time < NEW_TIME){
                return self::setError('活动已结束');
            }
            // 处理查询条件
            $record_where[] = $order_where[] = ['user_id', '=', $param['user_id']];
            if (!empty($beg_time) && !empty($end_time)){
                $order_where[] = ['order_time', 'between', [$rule['beg_time'], $rule['end_time']]];
                $record_where[] = ['create_time', 'between', [$beg_time, $end_time]];
            }
            if (!empty($beg_time) && empty($end_time)){
                $order_where[] = ['order_time', 'egt', $rule['beg_time']];
                $record_where[] = ['create_time', 'egt', $beg_time];
            }
            if (empty($beg_time) && !empty($end_time)){
                $order_where[] = ['order_time', 'elt', $rule['end_time']];
                $record_where[] = ['create_time', 'elt', $end_time];
            }
            // 已付款
            $order_where[] = ['status', '=', CoinOrder::isPay];
            // 查询是否已经兑换
            $record_where[] = ['number', '=', intval($param['number'])];
            $record_where[] = ['is_activity', '=', self::isJoin];
            $record_where[] = ['status', 'in', '0,1'];
            // 获取是否已兑换数据
            if ($this->getExists($record_where)){
                return self::setError('您已经兑换过了');
            }
            // 获取累充金额
            if (!empty($rule['activity_money'])){
                $activity_money = [];
                foreach ($rule['activity_money'] as $item){
                    if (floatval($item['value']) > 0 && floatval($item['key']) == floatval($param['number'])){
                        $activity_money = $item;
                        break;
                    }
                }
                if (empty($activity_money)){
                    return self::setError('充值失败，请联系客服');
                }
                // 获取用户活动期间累计充值金额
                $coin_order = new CoinOrder();
                $money = $coin_order->getSum($order_where, 'money');
                if (floatval($money) < floatval($activity_money['value'])){
                    $new_money = floatval($activity_money['value']) - floatval($money);
                    return self::setError('充值失败，还需充值' . $new_money . '元');
                }
            }
            $extend = $rule['activity_discount'];
        }else{
            if (!empty($rule['common_share'])){
                $activity_money = [];
                foreach ($rule['common_share'] as $item){
                    if (floatval($item['value']) > 0 && floatval($item['key']) == floatval($param['number'])){
                        $activity_money = $item;
                        break;
                    }
                }
                if (empty($activity_money)){
                    return self::setError('充值失败，请联系客服2');
                }
                // 查询今日累计兑换次数
                $beg_time = strtotime(date('Y-m-d', NEW_TIME));
                $record_where = [
                    ['create_time', '>=', $beg_time],
                    ['number', '=', intval($param['number'])],
                    ['is_activity', '=', self::unJoin],
                    ['status', 'in', '0,1']
                ];
                $exchange_count = $this->getCount($record_where);
                if ($exchange_count >= intval($activity_money['value'])){
                    return self::setError('兑换失败，今日次数已兑换完');
                }
            }
            $extend = $rule['ordinary'];
        }
        $price = 0;
        foreach ($extend as $item){
            if (intval($item['key']) == intval($param['number'])){
                $price = round(intval($item['key']) * floatval($item['value']) / 10, 2);
            }
        }
        // 获取当前用户帐号平台币
        $coin_model = new Coin();
        if (!$coin_model->compare($param['user_id'], $price)){
            return self::setError('兑换失败，平台币不足');
        }
        $record_data = [
            'order_code'=>'qb' . order_code(),
            'account'=>intval($param['account']),
            'number'=>intval($param['number']),
            'total'=>intval($param['number']),
            'price'=>$price,
            'user_id'=>$param['user_id'],
            'extend'=>json_encode($extend),
            'is_activity'=>$param['is_activity']
        ];
        $this->DbStartTrans();
        try {
            $result = $this->save($record_data);
            if ($result){
                // 扣除对应平台币
                $rows = $coin_model->coinDec($param['user_id'], $price, 'coin');
                if (!$rows){
                    $this->rollback();
                    return self::setError('兑换失败，请稍后重试');
                }
            }
            $this->commit();
        }catch (\Exception $e){
            $this->rollback();
            return self::setError($e->getMessage());
        }
        if ($result !== true){
            return self::setError('兑换失败，请稍后重试');
        }
        return [
            'order_code'=>$record_data['order_code'],
            'account'=>intval($param['account']),
            'number'=>$record_data['number'],
            'price'=>$price,
            'record_id'=>$this->getLastInsID()
        ];
    }

    public function topUpResult($param)
    {
        if (empty($param['record_id']) && empty($param['order_code'])){
            return false;
        }
        if (!empty($param['record_id'])){
            $where['record_id'] = $param['record_id'];
        }else{
            $where['order_code'] = $param['order_code'];
        }
        $record_data = $this->getFind($where);
        if (empty($record_data)) return false;
        if ($record_data['status'] != self::EXCHANGE_IN){
            return false;
        }
        $this->DbStartTrans();
        try {
            $this->setField($record_data['record_id'], [
                'remark'=>$param['remark'],
                'status'=>$param['status']
            ]);
            // 充值失败
            if ($param['status'] == self::EXCHANGE_FAIL){
                // 退回对应平台币
                $coin_model = new Coin();
                $rows = $coin_model->coinInc($param['user_id'], $record_data['price'], 'coin');
                if (!$rows){
                    $this->rollback();
                    return false;
                }
            }
            $this->commit();
        }catch (\Exception $e){
            $this->rollback();
            return false;
        }
        return true;
    }

    public function getIsUse($rule, $user_id, $number)
    {
        // 获取用户活动期间累计充值金额
        $where['user_id'] = $user_id;
        if (!empty($beg_time) && !empty($end_time)){
            $where['create_time'] = ['between', [$rule['beg_time'], $rule['end_time']]];
        }
        if (!empty($beg_time) && empty($end_time)){
            $where['create_time'] = ['egt', $rule['beg_time']];
        }
        if (empty($beg_time) && !empty($end_time)){
            $where['create_time'] = ['elt', $rule['beg_time']];
        }
        $where['number'] = $number;
        return $this->getExists($where);
    }

}